/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \src\pages\SystemSettings\StatementOfAccountConfig\EconomicBusinessConfig\components\AddHanderForm.tsx
 * @Date: 2022-03-17 21:22:42
 * @LastEditTime: 2022-04-13 11:51:39
 */
import UdSelect from '@/components/UdFormControls/UdSelect'
import { http, UdModalForm, validators } from '@/lib'
import { getSessionStorage } from '@/utils/methods'
import { useMount, useRafState, useSafeState } from 'ahooks'
import { Select } from 'antd'
import TextArea from 'antd/lib/input/TextArea'
import React, { useCallback } from 'react'
import apis from '@/apis/StatementOfAccount'
import CalcFormula from './CalcFormula'
import PlanTable from './PlanTable'
const { Option } = Select

interface IProps {
  calcType: object
  handType: object
  id?: number
  [Key: string]: any
}

type formValuesType = {
  valueType: string
  [Key: string]: any
}

const AddHanderForm = (props: IProps) => {
  const FINANCIAL_FIELD = getSessionStorage('FINANCIAL_FIELD') ?? []
  const { calcType: CALC_TYPE, handType: HAND_TYPE, id, ...rest } = props
  const labelCol: any = { span: 4 }
  const [calcConditionList, setCalcConditionList] = useSafeState<Array<any>>([])
  const [formValues, setFormValues] = useRafState<formValuesType>({ valueType: '0' })
  useMount(() => {
    id && getEconomicBusinessDetail(id)
  })

  const getEconomicBusinessDetail = (id: number): void => {
    http.get(apis.queryEconomicBusinessById, { params: { id } }).then(res => {
      let { data: { valueType, projectName, remarks, letterCalculationOn, result, letterCalculationTw } = {} } = res
      let params: formValuesType = { valueType, projectName, remarks }
      if (valueType === '0') {
        params['valueResult'] = letterCalculationOn[0]['calculationOn']
      } else if (valueType === '2') {
        params['calcFormula'] = { result: result, letterCalculationTw }
        params['letterCalculationOn'] = letterCalculationOn
      }
      console.log('params', params)
      setFormValues(params)
    })
  }

  const updateCalcConditionList = (list: Array<any> = []) => {
    setCalcConditionList([...list])
  }

  const getFinancialField = (type = 0) => {
    if (type === 0) {
      // UdSelect-options =>Object
      return FINANCIAL_FIELD.map(({ code, value }) => ({ value: code, title: value }))
    } else {
      // Select-options =>ReactNode
      return FINANCIAL_FIELD.map(({ code, value }) => (
        <Option value={code} key={code}>
          {value}
        </Option>
      ))
    }
  }

  const getCalcType = () => {
    const keys: ReadonlyArray<any> = Object.keys(CALC_TYPE)
    return keys.map(item => ({ value: item, title: CALC_TYPE[item] }))
  }

  const getHandType = () => {
    const keys: ReadonlyArray<any> = Object.keys(HAND_TYPE)
    return keys.map(item => ({ value: item, title: HAND_TYPE[item] }))
  }

  const getSourceCalcType = () => {
    return calcConditionList.map(item => (
      <Option value={item.vid + ''} key={item.vid}>
        {item.name}
      </Option>
    ))
  }

  const memoizedGetCalcType = useCallback(getCalcType, [CALC_TYPE])
  const memoizedGetHandType = useCallback(getHandType, [HAND_TYPE])
  const memoizedGetSourceCalcType = useCallback(getSourceCalcType, [calcConditionList])
  let { valueType: type } = formValues
  return (
    <UdModalForm
      {...rest}
      key={type}
      labelCol={labelCol}
      values={formValues}
      items={[
        { id: 'projectName', label: '项目名称', rules: [validators.required] },
        {
          id: 'valueType',
          label: '取值方式',
          rules: [validators.required],
          render: (
            <UdSelect
              options={memoizedGetCalcType()}
              showSearch={true}
              optionFilterProp="children"
              onChange={value => {
                setFormValues({ ...formValues, valueType: value })
              }}
            />
          ),
        },
        { id: 'remarks', label: '描述信息', render: <TextArea rows={3} maxLength={200} /> },
        type === '0' && {
          id: 'valueResult',
          label: '取值结果',
          rules: [validators.required],
          render: <UdSelect options={getFinancialField()} showSearch={true} optionFilterProp="children" />,
        },
        type === '2' && {
          id: 'letterCalculationOn',
          label: '计算条件',
          rules: [validators.required],
          render: (
            <PlanTable
              formValues={formValues}
              getFinancialField={getFinancialField}
              memoizedGetHandType={memoizedGetHandType}
              updateCalcConditionList={updateCalcConditionList}
            />
          ),
        },
        type === '2' && {
          id: 'calcFormula',
          label: '计算公式',
          rules: [validators.required],
          render: (
            <CalcFormula
              memoizedGetHandType={memoizedGetHandType}
              memoizedGetSourceCalcType={memoizedGetSourceCalcType}
              getFinancialField={getFinancialField}
            />
          ),
        },
      ].filter(item => typeof item !== 'boolean')}
    />
  )
}

export default React.memo(AddHanderForm)
